﻿
//***********************************************************************
// * Module:   TbBstCaseApplyHandler
// * 作者:  曹荣芝
// * Modified: 2014/6/1
// * Purpose: Definition of the Class TbBstCaseApplyHandler 业务逻辑处理Handler类
// ***********************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using XWG.Framework.MSException;
using XWG.Framework.AuthUtility;
using XWG.Framework.AuthEntity;
using XWG.Framework.AuthSPConst;
using XWG.Framework.AuthBLL;
using XWG.JWBST.JWBSTEntity;
using XWG.JWBST.JWBSTSPConst;
using System.Web.Script.Serialization;
using System.Data;
using XWG.Framework.Query;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using XWG.JWBST.JWBSTBLL;
using XWG.Framework;
using System.Collections;
using JWBSTAPP.CommonClass;
namespace JWBSTAPP.AjaxServer
{
    /// <summary>
    /// TbBstCaseApplyHandler 的摘要说明
    /// </summary>
    public class TbBstCaseApplyHandler : JWBSTAPP.CommonClass.HttpHandlerBase, System.Web.SessionState.IRequiresSessionState
    {

        #region 添加记录
        /// <summary>
        /// 添加记录
        /// </summary>
        protected void AddRecord()
        {
            HttpContext context = HttpContext.Current;
            context.Response.ContentType = "text/plain";
            ResultModel mResultModel = new ResultModel(); //初始化返回类型
            try
            {

                TbBstCaseApply mTbBstCaseApply = new TbBstCaseApply();
                mTbBstCaseApply.Id = Guid.NewGuid().ToString(); //主键
                //mTbBstCaseApply.Username = context.Request.Form["texUsername"]; //用户名
                mTbBstCaseApply.Password = context.Request.Form["texPassword"]; //密码
                mTbBstCaseApply.Name = context.Request.Form["texName"]; //姓名
                mTbBstCaseApply.Idnumber = context.Request.Form["texIdnumber"]; //身份证号码
                mTbBstCaseApply.Tel = context.Request.Form["texTel"]; //联系电话
                mTbBstCaseApply.Serialnumber = XWG.JWBST.JWBSTBLL.TbBstFastprocessBLL.GetLSH("TB_BST_CASE_APPLY");
                mTbBstCaseApply.Isaudit = "0"; //是否验证通过  0 未通过 1 通过
                mTbBstCaseApply.Movesign = "0"; //同步标志
                mTbBstCaseApply.Ipaddress = GetWebClientIp(); //ip地址

                mResultModel = TbBstCaseApplyBLL.Insert(mTbBstCaseApply, context.Session["UserID"], true); //新建操作
                if (mResultModel.ISSucceed)
                {
                    //if (TbBstCaseTodoBLL.hasApplyid(mTbBstCaseApply.Id))
                    //{
                    //    TbBstCaseTodo todo = new TbBstCaseTodo();
                    //    todo.Applyid = mTbBstCaseApply.Id;
                    //    todo.Id = Guid.NewGuid().ToString();
                    //    todo.Movesign = "0";
                    //    todo.Status = "0";
                    //    TbBstCaseTodoBLL.Insert(todo, "todoinsert", false);
                    //}
                    //else
                    //{
                    //    TbBstCaseTodoBLL.UpdateTodoByapplyid(mTbBstCaseApply.Id);
                    //}
                }
                context.Response.Write(JsonConvert.SerializeObject(mResultModel)); //序列化后返回
            }
            catch (Exception ex)
            {
                MSEx.DealErr(ex, "");
                mResultModel.ErrorCode = -9999;
                mResultModel.ISSucceed = false;
                context.Response.Write(JsonConvert.SerializeObject(mResultModel)); //序列化后返回
            }
        }
        #endregion

        #region 删除记录
        /// <summary>
        /// 删除记录
        /// </summary>
        protected void DeleteRecord()
        {

            HttpContext context = HttpContext.Current;
            context.Response.ContentType = "text/plain";
            ResultModel mResultModel = new ResultModel(); //声明返回类型
            try
            {
                string[] arryParamKey = context.Request.Params["id"].ToString().Split(',');
                if (arryParamKey.Length == 0)
                {
                    mResultModel.ErrorCode = -9991;
                    mResultModel.ISSucceed = false;
                    context.Response.Write(JsonConvert.SerializeObject(mResultModel)); //序列化后返回    
                    return;
                }
                TbBstCaseApply mTbBstCaseApply = new TbBstCaseApply();
                foreach (var paramKey in arryParamKey)
                {
                    mResultModel = TbBstCaseApplyBLL.Delete(paramKey, context.Session["UserID"], true); //删除对应的信息
                }
                context.Response.Write(JsonConvert.SerializeObject(mResultModel)); ; //序列化后返回
            }
            catch (Exception ex)
            {
                MSEx.DealErr(ex, ""); //写入异常日志
                mResultModel.ErrorCode = -9999; //-9999代码是系统异常通用代码
                mResultModel.ISSucceed = false; //行为执行失败
                context.Response.Write(JsonConvert.SerializeObject(mResultModel)); //序列化后返回
            }

        }
        #endregion

        #region 修改记录
        /// <summary>
        /// 修改记录
        /// </summary>
        protected void EditRecord()
        {
            HttpContext context = HttpContext.Current;
            context.Response.ContentType = "text/plain";
            ResultModel mResultModel = new ResultModel(); //初始化返回类型
            TbBstCaseApply mTbBstCaseApply = new TbBstCaseApply();

            string paramKey = context.Request.Params["id"];
            try
            {

                if (string.IsNullOrEmpty(paramKey))
                {
                    mResultModel.ErrorCode = -9991;
                    mResultModel.ISSucceed = false;
                    context.Response.Write(JsonConvert.SerializeObject(mResultModel)); //序列化后返回    
                    return;
                }
                mTbBstCaseApply = TbBstCaseApplyBLL.Load(paramKey); //根据键值获取实体信息
                if (mTbBstCaseApply != null)
                {
                    mTbBstCaseApply.Username = context.Request.Form["texUsername"]; //用户名
                    mTbBstCaseApply.Password = context.Request.Form["texPassword"]; //密码
                    mTbBstCaseApply.Name = context.Request.Form["texName"]; //姓名
                    mTbBstCaseApply.Idnumber = context.Request.Form["texIdnumber"]; //身份证号码
                    mTbBstCaseApply.Tel = context.Request.Form["texTel"]; //联系电话
                    mTbBstCaseApply.Serialnumber = context.Request.Form["texSerialnumber"]; //案件流水号
                    mTbBstCaseApply.Isaudit = context.Request.Form["texIsaudit"]; //是否验证通过  0 未通过 1 通过
                    mTbBstCaseApply.Reason = context.Request.Form["texReason"]; //验证未通过原因
                    // mTbBstCaseApply.Auditdate = context.Request.Form["texAuditdate"]; //验证日期
                    mTbBstCaseApply.Movesign = context.Request.Form["texMovesign"]; //同步标志
                    mTbBstCaseApply.Ipaddress = context.Request.Form["texIpaddress"]; //ip地址

                    mResultModel = TbBstCaseApplyBLL.Update(mTbBstCaseApply, context.Session["UserID"], true); //新建操作
                }
                else
                {
                    mResultModel.ErrorCode = -9990; //没有获取所需的信息，信息可能已被删除
                    mResultModel.ISSucceed = false;

                }
                context.Response.Write(JsonConvert.SerializeObject(mResultModel)); //序列化后返回
            }
            catch (Exception ex)
            {
                MSEx.DealErr(ex, "");
                mResultModel.ErrorCode = -9999;
                mResultModel.ISSucceed = false;
                context.Response.Write(JsonConvert.SerializeObject(mResultModel)); //序列化后返回
            }
        }
        #endregion

        #region 获取实体记录
        /// <summary>
        /// 获取实体记录
        /// </summary>
        protected void GetModel()
        {
            HttpContext context = HttpContext.Current;
            context.Response.ContentType = "text/plain";
            Hashtable ht = new Hashtable();
            ResultModel mResultModel = new ResultModel(); //初始化返回类型
            string paramKey = context.Request.Params["id"];
            string json = "";
            string dmt = "";
            try
            {
                TbBstCaseApply mTbBstCaseApply = new TbBstCaseApply(); //声明实体
                if (!string.IsNullOrEmpty(paramKey))
                {
                    if (mTbBstCaseApply != null)
                    {
                        mTbBstCaseApply = TbBstCaseApplyBLL.Load(paramKey); //根据键值获取管理员

                        mTbBstCaseApply.Idnumber = DES.Decode(mTbBstCaseApply.Idnumber);
                        mTbBstCaseApply.Name = DES.Decode(mTbBstCaseApply.Name);
                        mTbBstCaseApply.Tel = DES.Decode(mTbBstCaseApply.Tel);
                        if (!string.IsNullOrEmpty(mTbBstCaseApply.Isaudit))
                        {
                            if (mTbBstCaseApply.Isaudit == "1")
                            {
                                mTbBstCaseApply.Isaudit = "未通过";
                            }
                            else if (mTbBstCaseApply.Isaudit == "2")
                            {
                                mTbBstCaseApply.Isaudit = "已通过";
                                mTbBstCaseApply.Reason = "已通过审核";
                            }
                            else
                            {
                                mTbBstCaseApply.Isaudit = "尚未验证";
                                mTbBstCaseApply.Reason = "尚未验证";
                            }
                        }
                        IsoDateTimeConverter dtConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
                        json = JsonConvert.SerializeObject(mTbBstCaseApply, dtConverter);
                        if (mTbBstCaseApply.Auditdate.ToString("yyyy") == "0001")
                        {
                            dmt = "暂无审核时间";
                            ht.Add("auditTime", dmt);
                        }
                        else
                        {
                            dmt = mTbBstCaseApply.Auditdate.ToString();
                            ht.Add("auditTime", dmt);
                        }                   
                        json = JsonString.AddAttribute(json, ht);
                    }
                }
            }
            catch (Exception ex)
            {
                MSEx.DealErr(ex, "");
                mResultModel.ErrorCode = -9990;
                mResultModel.ISSucceed = false;
                json = JsonConvert.SerializeObject(mResultModel);
            }
            context.Response.Write(json);
        }
        #endregion

        #region 获取数据
        /// <summary>
        /// 获取数据记录
        /// </summary>
        protected void QueryRecord()
        {
            TableMessage tm = new TableMessage();
            HearderMessage hm = new HearderMessage();
            List<HearderMessage> list = new List<HearderMessage>();
            HttpContext context = HttpContext.Current;
            context.Response.ContentType = "text/plain";
            string pageSize = context.Request.Form["pageSize"];
            string pageIndex = context.Request.Form["pageIndex"];
            if (String.IsNullOrEmpty(pageSize) || String.IsNullOrEmpty(pageIndex) || !AnyString.IsNumeric(pageSize) || !AnyString.IsNumeric(pageIndex))
                return;
            DataTable dtTbBstCaseApply = new DataTable();
            int intPageSize = Convert.ToInt32(pageSize);
            int intPageIndex = Convert.ToInt32(pageIndex);
            //string Name = DES.Encode(context.Request.Form["texName"]);         //用户名
            string lsh = context.Request.Form["texlsh"];
            string ZpCode = context.Request.Form["selStatus"];    //操作类型
            DateTime begintime = new DateTime();
            DateTime endtime = new DateTime();
            if (!string.IsNullOrEmpty(context.Request.Form["texTimeStart"]))
            {
                begintime = Convert.ToDateTime(context.Request.Form["texTimeStart"]);
            }
            if (!string.IsNullOrEmpty(context.Request.Form["texTimeEnd"]))
            {
                endtime = Convert.ToDateTime(context.Request.Form["texTimeEnd"]);
            }
            QueryByPage Q = new QueryByPage();
            QueryInfo qInfo = new QueryInfo();
            SqlConditionList sqllist = new SqlConditionList();
            if (!string.IsNullOrEmpty(lsh))
            {
                sqllist.AddLogic(new SqlConditionList.SqlCondition(SqlCompareOper.LIKE, TbBstCaseApplyConst.Columns.Username, '%' + lsh + '%'), SqlLogicOper.AND_LOGIC);
            }
            //if (!string.IsNullOrEmpty(Name))
            //{
            //    sqllist.AddLogic(new SqlConditionList.SqlCondition(SqlCompareOper.LIKE, TbBstCaseApplyConst.Columns.Name, '%' + Name + '%'), SqlLogicOper.AND_LOGIC);
            //}
            if (!string.IsNullOrEmpty(ZpCode))
            {
                sqllist.AddLogic(new SqlConditionList.SqlCondition(SqlCompareOper.EQUAL, TbBstCaseApplyConst.Columns.Isaudit, ZpCode), SqlLogicOper.AND_LOGIC);
            }
            if (begintime.ToString() != "0001/1/1 0:00:00")
            {
                sqllist.AddLogic(new SqlConditionList.SqlCondition(SqlCompareOper.NOT_LESS_THAN, TbBstCaseApplyConst.Columns.Createdate, begintime), SqlLogicOper.AND_LOGIC);
            }
            if (endtime.ToString() != "0001/1/1 0:00:00")
            {
                sqllist.AddLogic(new SqlConditionList.SqlCondition(SqlCompareOper.NOT_MORE_THAN, TbBstCaseApplyConst.Columns.Createdate, endtime), SqlLogicOper.AND_LOGIC);
            }
            dtTbBstCaseApply = Q.GetRecordByPage("*", sqllist.ToSql(), "CREATEDATE", intPageSize, intPageIndex, TbBstCaseApplyConst.TableName, TbBstCaseApplyConst.FieldKey, "DESC").Tables[0];
            for (int i = 0; i < dtTbBstCaseApply.Rows.Count; i++)
            {
                dtTbBstCaseApply.Rows[i]["NAME"] = DES.Decode(dtTbBstCaseApply.Rows[i]["NAME"].ToString());
                dtTbBstCaseApply.Rows[i]["IDNUMBER"] = DES.Decode(dtTbBstCaseApply.Rows[i]["IDNUMBER"].ToString());
                dtTbBstCaseApply.Rows[i]["TEL"] = DES.Decode(dtTbBstCaseApply.Rows[i]["TEL"].ToString());
                //if (!string.IsNullOrEmpty(dtTbBstCaseApply.Rows[i]["CREATEDATE"].ToString()))
                //{
                //    dtTbBstCaseApply.Rows[i]["CREATEDATE"] = dtTbBstCaseApply.Rows[i]["CREATEDATE"].ToString();
                //}
                string mes = "";
                string color = "";
                if (dtTbBstCaseApply.Rows[i]["ISAUDIT"].ToString() == "1")
                {
                    mes = "未通过";
                    color = "326AC9";
                }
                else if (dtTbBstCaseApply.Rows[i]["ISAUDIT"].ToString() == "2")
                {
                    mes = "已通过";
                    color = "32C904";
                }
                else
                {
                    mes = "待审核";
                    color = "326AC9";
                }
                dtTbBstCaseApply.Rows[i]["ISAUDIT"] = "<span style=\"color:#" + color + "\">" + mes + "</span>";
            }
            if (dtTbBstCaseApply != null && dtTbBstCaseApply.Rows.Count > 0)
            {
                for (int i = 0; i < dtTbBstCaseApply.Columns.Count; i++)
                {
                    hm = new HearderMessage();
                    hm.name = dtTbBstCaseApply.Columns[i].Caption;
                    list.Add(hm);
                }
                tm.Header = list;
                tm.data = dtTbBstCaseApply;
                tm.totalCount = Convert.ToString((int)Q.RowCount);
            }
            IsoDateTimeConverter dtConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
            string json = JsonConvert.SerializeObject(tm, dtConverter);
            context.Response.Write(json);
        }
        #endregion


        #region 获取web客户端ip
        /// <summary>
        /// 获取web客户端ip
        /// </summary>
        /// <returns></returns>
        public static string GetWebClientIp()
        {

            string userIP = "未获取用户IP";

            try
            {
                if (System.Web.HttpContext.Current == null
            || System.Web.HttpContext.Current.Request == null
            || System.Web.HttpContext.Current.Request.ServerVariables == null)
                    return "";

                string CustomerIP = "";

                //CDN加速后取到的IP simone 090805
                CustomerIP = System.Web.HttpContext.Current.Request.Headers["Cdn-Src-Ip"];
                if (!string.IsNullOrEmpty(CustomerIP))
                {
                    return CustomerIP;
                }

                CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];


                if (!String.IsNullOrEmpty(CustomerIP))
                    return CustomerIP;

                if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
                {
                    CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                    if (CustomerIP == null)
                        CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                }
                else
                {
                    CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

                }

                if (string.Compare(CustomerIP, "unknown", true) == 0)
                    return System.Web.HttpContext.Current.Request.UserHostAddress;
                return CustomerIP;
            }
            catch { }

            return userIP;

        }
        #endregion

    }
}


